package com.example.sysao.controller;

import com.example.sysao.pejo.Repair;
import com.example.sysao.pejo.Student;
import com.example.sysao.service.MaintenanceService;
import com.example.sysao.service.ReapirService;
import com.example.sysao.service.UrgentService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@Component
@RequestMapping("/repair")
public class RepairController {
    @Resource
    private UrgentService urgentService;
    @Resource
    private ReapirService reapirService;
    @Resource
    private MaintenanceService maintenanceService;


    @RequestMapping("/list")
    public List<Repair> findAll() {
        return reapirService.findAll();
    }

    @RequestMapping("/findById")
    public Repair findById(int id) {
        return reapirService.findById(id);
    }

    @RequestMapping("/addRepair")
    public Map<String, Object> addSavefile(String detail, String place, MultipartFile file, HttpSession session) throws IOException {
        //定义路径
        String basePath = "E:/uplode";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyMMdd");
        String dateStr = fmt.format(new Date());//得到20030105
        String dir = basePath + "/" + dateStr;//存放的路径
        new File(dir).mkdirs();//生成目录保证有目录
        //取得后缀名，在拼接上唯一名称
        String fileType = StringUtils.getFilenameExtension(file.getOriginalFilename());//获得文件扩展名
        String localPath = "/" + dateStr + "/" + UUID.randomUUID() + "." + fileType;//UUID生成唯一的字符串
        LocalDateTime time = LocalDateTime.now();
        Repair repair = new Repair();
        repair.setPlace(place);
        repair.setDetail(detail);
        repair.setStatus(1);
        repair.setSubmitTime(time);
        repair.setPicMD5(localPath.toLowerCase());

        String path = basePath + localPath;//绝对路径本地位置
        file.transferTo(new File(path));//文件通道保存
        Student student = (Student) session.getAttribute("student");
        repair.setStudentId(student.getId());

        Map<String, Object> map = new HashMap<>();
        if (reapirService.addRepair(repair)) {
            map.put("success", true);
        }
        return map;

    }


    @RequestMapping("/inaddRepair")
    public Map<String, Object> inaddRepair(String detail, String place, int studentId, MultipartFile file, HttpSession session) throws IOException {
        //定义路径
        String basePath = "E:/uplode";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyMMdd");
        String dateStr = fmt.format(new Date());//得到20030105
        String dir = basePath + "/" + dateStr;//存放的路径
        new File(dir).mkdirs();//生成目录保证有目录
        //取得后缀名，在拼接上唯一名称
        String fileType = StringUtils.getFilenameExtension(file.getOriginalFilename());//获得文件扩展名
        String localPath = "/" + dateStr + "/" + UUID.randomUUID() + "." + fileType;//UUID生成唯一的字符串
        LocalDateTime time = LocalDateTime.now();
        Repair repair = new Repair();
        repair.setPlace(place);
        repair.setDetail(detail);
        repair.setStatus(1);
        repair.setSubmitTime(time);
        repair.setPicMD5(localPath.toLowerCase());

        String path = basePath + localPath;//绝对路径本地位置
        file.transferTo(new File(path));//文件通道保存
        Student student = (Student) session.getAttribute("student");
        repair.setStudentId(studentId);
        Map<String, Object> map = new HashMap<>();
        if (reapirService.addRepair(repair)) {
            map.put("success", true);
        }
        return map;

    }


    @RequestMapping("/downlode/{id}")
    public ResponseEntity<FileSystemResource> downlode(@PathVariable("id") int id) throws UnsupportedEncodingException {
        //  SaveFile saveFile = saveFileService.findById(id);
        Repair repair = reapirService.findById(id);
        if (repair != null) {
            String basePath = "E:/uplode";
            String Path = basePath + repair.getPicMD5();//本地的路径
            File file = new File(Path);
            if (file.isFile()) {//文件存在
                //通知浏览器返回的是文件
                //设置消息头
                HttpHeaders headers = new HttpHeaders();
                String name = new String(repair.getDetail().getBytes(), "iso-8859-1");
                headers.add("Content-Type", "application/octet-stream");
                headers.add("Content-Disposition", "attachment; filename=" + repair.getDetail());
                return ResponseEntity.ok().headers(headers)
                        .contentLength(file.length()).body(new FileSystemResource(file));
            }
        }
        return null;
    }

    @DeleteMapping("/deleteRepair/{userId}")
    public Map<String, Object> deleteuser(@PathVariable("userId") int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        if (reapirService.removeRepair(id)) {
            urgentService.removeUrgentr(id);
            maintenanceService.removeMaintencebyRid(id);
            map.put("success", true);
        }
        return map;
    }

    @DeleteMapping("/remove")
    public Map<String, Object> remove(int[] ids) {
        for (int id : ids) {
            reapirService.removeRepair(id);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        return map;
    }

    @PostMapping("/findbydetail")
    public List<Repair> findbydetail(String detail) {
        return reapirService.findByDetail(detail);
    }


    @PostMapping("/updateRepair")
    public Map<String, Object> saveuser(@RequestBody Repair repair) {
        Map<String, Object> map = new HashMap<>();
        if (reapirService.saveRepair(repair)) {
            map.put("success", true);
        }
        return map;
    }

    //多条件查询
    @RequestMapping("/findByKeywords")
    public List<Repair> findBname(String detail, String place) {
        List<Repair> list = new ArrayList<>();
        list = reapirService.selectByKeyWords(detail, place);
        return list;
    }

    //根据状态号查询
    @RequestMapping("/findByStatus")
    public List<Repair> findByStatus() {
        return reapirService.findByid();
    }


    //admin查询
    //查询未完成
    @RequestMapping("/unfinished")
    public List<Repair> findUnfinished(int page, int size) {
        List<Integer> ids = new ArrayList<>();
        int offset = page * size + 1;
        List<Repair> list = reapirService.findByStatus1(offset, size);
        for (int i = 0; i < list.size(); i++) {
            Repair repair = list.get(i);

            ids.add(repair.getId());
        }

        List<Repair> repairlist = new ArrayList<>();
        for (int id : ids) {
            Repair repair1 = reapirService.findById(id);
            repairlist.add(repair1);
        }
        return repairlist;
    }

    @RequestMapping("/unfinishedAll")
    public List<Repair> unfinishedAll() {
        List<Integer> ids = new ArrayList<>();

        List<Repair> list = reapirService.findByStatus1();
        for (int i = 0; i < list.size(); i++) {
            Repair repair = list.get(i);

            ids.add(repair.getId());
        }

        List<Repair> repairlist = new ArrayList<>();
        for (int id : ids) {
            Repair repair1 = reapirService.findById(id);
            repairlist.add(repair1);
        }
        return repairlist;
    }

    @RequestMapping("/accomplish")
    public List<Repair> findaccomplish() {
        List<Integer> ids = new ArrayList<>();
        List<Repair> list = reapirService.findByStatus2();
        for (int i = 0; i < list.size(); i++) {
            Repair repair = list.get(i);
            ids.add(repair.getId());
        }
        List<Repair> repairlist = new ArrayList<>();
        for (int id : ids) {
            Repair repair1 = reapirService.findById(id);
            repairlist.add(repair1);
        }
        return repairlist;
    }

    //验收
    @RequestMapping("/check")
    public Map<String, Object> checklRepair(Integer id) {
        //更改维修状态为6
        Repair repair = reapirService.findById(id);
        repair.setStatus(6);
        Map<String, Object> map = new HashMap<>();
        if (reapirService.saveRepair(repair)) {
            map.put("success", true);
        }
        return map;
    }
}
